from PIL import Image, ImageEnhance, ImageFilter
import pytesseract
import re
from bs4 import BeautifulSoup
from urllib.parse import unquote


# 设置 Tesseract OCR 的路径（请根据您的实际安装路径进行更改）
pytesseract.pytesseract.tesseract_cmd = r"D:\Program Files\Tesseract-OCR\tesseract.exe"


def read_captcha(image_path):
    # 打开图像文件
    image = Image.open(image_path)
    # image = image.resize((200, 200))
    # image = image.convert("L")
    # enhancer = ImageEnhance.Contrast(image)
    # image = enhancer.enhance(2.0)
    # image = image.filter(ImageFilter.SHARPEN)
    # threshold_value = 200

    # image = image.resize((200, 200))
    # image = image.convert("L")
    # enhancer = ImageEnhance.Contrast(image)
    # image = enhancer.enhance(2.0)
    image = image.filter(ImageFilter.SHARPEN)
    threshold_value = 200
    image = image.point(lambda p: p > threshold_value and 255)

    # image = image.point(lambda p: p > threshold_value and 9999)
    custom_config = r"--oem 3 --psm 9 outputbase digits --lang eng"
    # 使用 Tesseract OCR 识别文本
    text = pytesseract.image_to_string(image, config=custom_config)
    result = re.sub(r"[^a-zA-Z0-9]", "", text)
    return result


def html_to_playList(html):
    soup = BeautifulSoup(html, "html.parser")
    play_type_elements = soup.find_all(
        lambda tag: tag.name == "h3" and tag.text.startswith("播放类型")
    )
    data_objects = []
    for index, play_type_element in enumerate(play_type_elements, start=1):
        # Find the <a> element within the corresponding <ul>
        ul_element = play_type_element.find_next("ul")
        a_elements = ul_element.find_all("a")

        # Extract href value from the first <a> element
        href_value = a_elements[0]["href"]
        onclick_value = a_elements[1].get("onclick")
        match = re.search(r'"([^"]*?)https://', onclick_value)
        extracted_text = match.group(1).strip()
        data_objects.append({"url": href_value, "text": extracted_text})
        # Extract the text content from the second <a> element
        # name_text = a_elements[1].get_text(strip=True)
    return data_objects


def html_to_playList2(html):
    soup = BeautifulSoup(html, "html.parser")
    play_type_elements = soup.find_all(
        lambda tag: tag.name == "h3" and tag.text.startswith("播放类型")
    )
    data_objects = []
    for index, play_type_element in enumerate(play_type_elements, start=1):
        # Find the <a> element within the corresponding <ul>
        ul_element = play_type_element.find_next("ul")
        li_element = ul_element.find_all("li")
        for li in li_element:
            a_elements = li.find_all("a")

            # Extract href value from the first <a> element
            href_value = a_elements[0]["href"]
            onclick_value = a_elements[1].get("onclick")
            match = re.search(r'"([^"]*?)https://', onclick_value)
            extracted_text = match.group(1).strip()
            data_objects.append({"url": href_value, "text": extracted_text})
        # Extract the text content from the second <a> element
        # name_text = a_elements[1].get_text(strip=True)
    return data_objects


def html_to_playOne(html, series):

    # full_string = "mac_urlx10d26=unescape('HD%u4e2d%u5b57%u7248%24https%3A%2F%2Fcdn20.vip-vip-yzzy.com%2Fshare%2Fbc1ad6e8f86c42a371aff945535baebb%24%24%24HD%u4e2d%u5b57%u7248%24https%3A%2F%2Fcdn20.vip-vip-yzzy.com%2F20231128%2F6347_aa72110c%2Findex.m3u8')"
    full_string = html
    # Extract the data between unescape(' and ')
    start_index = full_string.find("unescape('") + len("unescape('")
    end_index = full_string.find("')", start_index)

    #

    # Get the substring
    substring = full_string[start_index:end_index]
    if series is None:
        start_index = substring.rfind("https")
        decoded_data = unquote(substring[start_index:])
        # print(f"Decoded Data: {decoded_data}")
        return decoded_data
    else:
        # print(f"Decoded Data: {decoded_data}")
        # print(f"Series: {series}")
        start_index = (
            substring.rfind("%u7b2c" + series + "%u96c6") + len("%u7b2c" + series + "%u96c6") + 1
        )
        start_index = substring.find("http", start_index)
        end_index = substring.find(".m3u8", start_index) + len(".m3u8")
        decoded_data = unquote(substring[start_index:end_index])
        # print(f"Decoded Data: {decoded_data}")
        return decoded_data


if __name__ == "__main__":
    # 图片路径（请替换为您实际的验证码图片路径）
    captcha_image_path = "e://code.jpg"

    # 读取验证码
    captcha_text = read_captcha(captcha_image_path)

    # 打印识别结果
    print("识别结果:", captcha_text)
    # html_to_playOne("")
